package com.study.d12_tcp_mul3;

import java.io.*;
import java.net.Socket;

public class ServerReaderThread extends Thread{
    private Socket socket;
    public ServerReaderThread(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            DataInputStream dis = new DataInputStream(inputStream);
            while(true){
                try{
                    String msg = dis.readUTF();
                    System.out.println(msg);
                    //把这个消息发给全部客户端接收
                    sendAllMsg(msg);
                }catch (Exception e) {
                    System.out.println(socket.getRemoteSocketAddress()+"下线了");
                    Server.onlineSockets.remove(socket);
                    inputStream.close();
                    dis.close();
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void sendAllMsg(String msg) throws Exception {
        //发送给全部在线的socket管道接收
        for (Socket onlineSocket : Server.onlineSockets) {
            OutputStream outputStream = onlineSocket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(outputStream);
            dos.writeUTF(msg);
            dos.flush();
        }
    }
}
